package dp;

/**
 * 最长回文子串,给你一个字符串 s，找到 s 中最长的回文子串。
 * dp [0][n] 为字符长度0-n的最长回文串长度
 * dp [0][n]= max{[dp[1][n-1], dp[1][n-1]+2]}
 */
public class P5 {
    public String longestPalindrome(String s) {
        if (s == null || s.length() == 1) {
            return s;
        }
        int len = s.length();
        int start = 0;
        int maxLen = 1;
        boolean[][] dp = new boolean[len][len];
        // 1. 初始化赋值
        for (int i = 0; i < len; i++) {
            dp[i][i] = true;
        }

        // 2. 依据字串长度逐渐递增
        char[] chars = s.toCharArray();
        for (int L = 2; L <= len; L++) {
            for (int begin = 0; begin < len; begin++) {
                int end = begin + L - 1;
                if (end >= len) {
                    break;
                }
                if (chars[begin] != chars[end]) {
                    dp[begin][end] = false;
                } else {
                    if (end - begin < 2) {
                        dp[begin][end] = true;
                    }else{
                        dp[begin][end] = dp[begin + 1][end - 1];
                    }
                }

                if (dp[begin][end] && end - begin + 1 > maxLen) {
                    maxLen = end - begin + 1;
                    start = begin;
                }
            }
        }
        return s.substring(start, start + maxLen);
    }

    public static void main(String[] args) {
        String sub = new P5().longestPalindrome("cbbd");
        System.out.println(sub);
    }
}
